/*
 * @Author: zhangguowei 974599791@qq.com
 * @Date: 2022-08-25 11:38:28
 * @LastEditors: zhangguowei 974599791@qq.com
 * @LastEditTime: 2022-08-29 15:16:29
 * @Description:封装请求函数
 */
import { AxiosRequestConfig, AxiosPromise } from "axios";
import { useRequst } from "@/utils/request";
const { request } = useRequst();

// 需要与后端约定好的公共的返回类型
interface Response<T = any> {
  data: T;
  code: Code;
  message: string;
  [key: string]: any;
}
interface RequestConfig {}
type Code = 404 | 500 | 200;
type HttpType = "get" | "post";

const createRequestMethod = (type: HttpType) => {
  return <T, P>(url: string, config?: AxiosRequestConfig) => {
    return (data: T): AxiosPromise<Response<P>> => {
      let options = { ...config, url };
      if (type == "get") {
        options.method = "get";
        options.params = data;
      } else if (type == "post") {
        options.method = "post";
        options.data = data;
      }
      return request(options);
    };
  };
};

const getfn = createRequestMethod("get");
const postfn = createRequestMethod("post");

// 使用hook写法
const useAxios = () => {
  return {
    getfn,
    postfn,
  };
};

export { useAxios };
